﻿using System;

using System.Collections.Generic;
using System.Text;
using System.Drawing;
using Silvermoon.Visuals;
using Silvermoon.Utils;
using Silvermoon.OpenGL;

namespace Silvermoon.Controls
{
    /// <summary>
    /// Special Item to provide a header in a <see cref="T:ListViewBase"/>. A ItemHeader has a special function in a ListViewBase:
    /// When available, the ListView always shows the last ItemHeader as top item.
    /// </summary>
    public class ItemHeader : ItemBase
    {
        public const int DefaultHeaderHeight = 32;

        #region Fields

        private string text = String.Empty;
        private BackgroundVisual background;
        private StringVisual stringVisual;
        private Color color;

        #endregion
        #region ctor

        public ItemHeader()
            : base()
        {
            background = new BackgroundVisual();
            stringVisual = new StringVisual { Color = Color.White, CharSpace = 2, Alignment = Alignment.Center, LineAlignment = Alignment.Center, LineMode = LineMode.SingleLineEndElipsis };
            TextColor = SysColors.ItemHeaderTextColor;
            color = SysColors.ItemHeaderColor;


            Visuals = new Visual[] { background, stringVisual };
            size = new Size(0, DefaultHeaderHeight);
        }

        #endregion
        #region Props

        public string Text { get { return text; } set { if (text != value) { text = value; Invalidate(InvalidationFlag.Text); } } }

        public Color Color { get { return color; } set { if (color != value) { color = value; Invalidate(InvalidationFlag.Color); } } }

        #endregion
        #region methods

        protected override void OnSizeChanged()
        {
            if (Height != DefaultHeaderHeight) Size = new Size(Size.Width, DefaultHeaderHeight);
            else
            {
                base.OnSizeChanged();
            }
        }

        private void SetTextBounds()
        {
            background.Size = Control.Scale(Size);
            stringVisual.Bounds = Control.ScaledRect(2, 2, Width - 4, Height - 4);
        }

        protected override void OnLayout()
        {
            if ((InvalidationMask & InvalidationFlag.Color) != 0) background.Colors = ColorUtil.CreateGradientColor(color);
            stringVisual.Text = text;
            if (CheckFlag(InvalidationFlag.TextColor))
            {
                stringVisual.Color = TextColor;
            }

            if (CheckFlag(InvalidationFlag.Size | InvalidationFlag.Margin))
            {
                SetTextBounds();
            }
            base.OnLayout();
        }

        #endregion
    }
}
